#!/usr/bin/ruby -d


require 'tstorage'
require '/var/lib/gems/1.8/gems/chronic-0.2.3/lib/chronic'

class Mail

  def process
    if (header['From'] =~ /<(\S+@\S+)>/)
      @submitter = $1
    else
      raise ArgumentError, "Unknown submitter", header['From']
    end
    @subject   = header['Subject']
    @request   = header['To']
    if @request =~ /submit/i 
      @submit = 1
    elsif @request =~ /remind/i
      @submit = 0
    else
      raise ArgumentError,
            "Unknown destination address in Mail.initialize.",
            caller
    end
    body.each do |line|
      break if (line =~ /--\n/ || line =~ /^thank\w*\n/)
      if line =~ /^Date:\s*(.+)$/
        arg = $1
        if arg =~ /(\d\d\d\d-\d\d-\d\d)\s+(\d{1,2}:\d\d)/
          @date = $1
          timeofday = $2
        elsif arg =~ /(\w+)\s+(.+)$/
          something = $1
          timeofday = $2
          if !(@date = Chronic.parse(something).strftime("%Y-%m-%d"))
            raise ArgumentError, "Can't parse date. YYYY-MM-DD or day of week expected."
          end
        else
          raise ArgumentError, "Wrong date. YYYY-MM-DD or day of week expected."
        end
        if timeofday =~ /(\d{1,2}):(\d\d)/
          hour = $1
          minute = $2
          if hour.to_i < 10
            hour = "0#{hour}"
          end
          if (minute.to_i > 59 || hour.to_i > 23)
            raise ArgumentError, "To much minutes or hours in 'Date:' directive"
          end
          @time = "#{hour}:#{minute}"
        else
          @time = "12:00"
        end
      end
    end
    if @submit
      tstor = TaskStorage.instance
      tstor.store(@submitter, @subject, @date, @time)
    else
      rem = Reminder.new(@submitter, @subject)
      rem.send
    end
  end
end

